<?php
namespace app\api\service;
use Green\Request\V20170112\ImageScanFeedbackRequest;
use think\Controller;
use think\Db;
use think\Exception;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/26 0026
 * Time: 15:40
 */

class Rong extends Controller {

    /**
     * 获取账户融云信息
     * @param $param
     * @return array
     */
    public static function get_member_rong_info($param) {
        try {
            $data = model('rong_member_info')->get(['member_id' => $param['member_id']]);
            if (!$data) {
                $data = self::get_rong_member_token($param['member_id']);
            }

            if (isset($param['targetId'])) {
                $target_data = model('rong_member_info')->get(['member_id' => $param['targetId']]);
                if (!$target_data) {
                    $target_data = self::get_rong_member_token($param['member_id']);
                }
//                if (isset($param['role']) && $param['role'] == 'shop') {
//                    $shop = model('shop')->get(['member_idmember_id' => $param['targetId']]);
//                    $target_data['name'] = $shop['name'];
//                    $target_data['portraitUri'] = get_img_url($shop['logo']);
//                }

                $data['target'] = $target_data;
            }

            if (!$data['portraitUri']) {
                $member_role_info = model('member_role_info')->where('member_id', $param['member_id'])->find();
                if (!$member_role_info['headimgurl']) {
                    $data['portraitUri'] = '/static/home/images/pay.png';
                }
                else {
                    $data['portraitUri'] = $member_role_info['headimgurl'];
                }
            }

            if (isset($param['type'])) {
                $data['type'] = $param['type'];
                if ($data['type'] == 'kefu') {
                    // 客服消息应该要重新定义  待定
                }
            }

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    private static function get_rong_member_token($member_id) {
        $member = model('member')->get(['id' => $member_id]);
        // 信息不存在，通过接口获取
        $accid = $member_id;

        // 接口参数
        $str = 'userId=' . $accid . '&name=' . $member->memberRoleInfo->nickname . '&portraitUri=' . $member->memberRoleInfo->headimgurl;
        $url = 'http://api.cn.ronghub.com/user/getToken.json';

        $data = self::https_request($url, $str);

        model('rong_member_info')->save(['member_id' => $member_id, 'userId' => $data['userId'], 'token' => $data['token'], 'name' => $member->memberRoleInfo->nickname, 'portraitUri' => $member->memberRoleInfo->headimgurl]);

        // 重新获取一下数据
        $data = model('rong_member_info')->get(['member_id' => $member_id]);

        return $data;
    }

    /**
     * 获取用户好友列表
     * @param $param
     * @return array
     */
    public static function get_member_rong_friend($param) {
        try {
            $friends = model('rong_member_friend')->where('user_id', $param['member_id'])->select();

            $f_list = [];
            $g_list = [];
            foreach ($friends as $k => $v) {
                if($v['type'] == 'friend') {
                    $f_list[$v['group']][] = [
                        "username" => $v->memberFriend->memberRoleInfo->nickname
                        , "id" => $v->target_id
                        , "avatar" => $v->memberFriend->memberRoleInfo->headimgurl
                        , "sign" => $v->memberFriend->rong->sign
                    ];
                } else {
                    $g_list[] = [
                        "username" => $v->memberGroup->name
                        , "id" => $v->target_id
                        , "avatar" => $v->memberGroup->image_1
                    ];
                }
            }

            $friend_list = [];
            if (isset($f_list['friend'])) {
                $friend_list[] = [
                    "groupname" => "好友"
                    , "id" => 1
                    , "list" => $f_list['friend']
                ];
            }

            if (isset($f_list['kefu'])) {
                $friend_list[] = [
                    "groupname" => "客服"
                    , "id" => 2
                    , "list" => $f_list['kefu']
                ];
            }

            $data['friend'] = json_encode($friend_list);
            $data['group'] = json_encode($g_list);

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 创建群组
     * @param $param
     * @return array
     */
    public static function create_group($param) {
        Db::startTrans();
        try {
            $activity = model('activity')->get(['id' => $param['id']]);
            if ($activity->group_id) {
                throw new \Exception('本活动已经创建群组');
            }

            // 发起者用户信息
            $accid = $activity->member_id;

            // 接口参数
            $str = 'userId=' . $accid . '&groupId=' . $activity->id . '&groupName=' . $activity->name;
            $url = 'http://api.cn.ronghub.com/group/create.json';

            $data = self::https_request($url, $str);
            if ($data['code'] == 200) {
                model('activity')->save(['group_id' => $activity->id], ['id' => $param['id']]);
                $rong_member_info = Rong::get_member_rong_info_by_userId(['userId' => $accid]);
                // 添加一条关系数据  当前用户最为发起发  群ID做为接收方
                model('rong_member_relation')->save([
                    'userId' => 'jx_rong_' . $activity->member_id,
                    'targetId' => 'activity_' . $activity->id,
                    'target_headimgurl' => $rong_member_info['code'] == 200 ? $rong_member_info['data']['headimgurl'] : '',
                    'target_nickname' => $rong_member_info['code'] == 200 ? $rong_member_info['data']['nickname'] : '',
                    'type' => 3
                ]);
            }
            Db::commit();
            return $data;
        } catch (\Exception $e) {
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 加入群组
     * @param $param
     * @return array
     */
    public static function join_group($param) {
        try {
            // 接口参数
            $str = 'userId=' . $param['userId'] . '&groupId=' . $param['groupId'] . '&groupName=' . $param['groupName'];
            $url = 'http://api.cn.ronghub.com/group/join.json';

            $data = self::https_request($url, $str);
            return $data;
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * CURL请求
     * @param $url
     * @param $str
     * @return mixed
     */
    protected static function https_request($url, $str)
    {
        // 获取签名数据
        $request_header = self::computeSignature();

        //$url = 'http://api.cn.ronghub.com/user/getToken.json';
        $headers = array();
        array_push($headers, "App-Key:" . config('rong.app_key'));
        array_push($headers, "Nonce:$request_header[nonce]");
        array_push($headers, "Timestamp:$request_header[timestamp]");
        array_push($headers, "Signature:$request_header[signature]");

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $str);

        if (1 == strpos("$" . $url, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $rs = curl_exec($curl);

        // 获得响应结果里的：头大小
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        // 根据头大小去获取头信息内容
        $header = substr($rs, $headerSize);

        return $data = json_decode($header, true);
    }

    /**
     * xml数据转换成数组
     * @param $xml
     * @return mixed
     */
    protected static function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
                $subxml= $matches[2][$i];
                $key = $matches[1][$i];
                if(preg_match( $reg, $subxml )){
                    $arr[$key] = self::xml_to_array( $subxml );
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return @$arr;
    }

    /**
     * 签名
     * @return array
     */
    protected static function computeSignature()
    {
        // 重置随机数种子。
        srand((double)microtime()*1000000);

        $appSecret = config('rong.app_secret'); // 开发者平台分配的 App Secret。
        $nonce = rand(); // 获取随机数。
        $timestamp = time(); // 获取时间戳。

        $signature = sha1($appSecret.$nonce.$timestamp);

        return [
            'appSecret' => $appSecret,
            'nonce' => $nonce,
            'timestamp' => $timestamp,
            'signature' => $signature,
        ];
    }

    /**
     * 处理编码
     * @param $str
     * @return mixed|string
     */
    protected static function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    /**
     * 保存融云消息记录
     * @param $param
     * @return array
     */
    public static function save_rong_msg($param) {
        Db::startTrans();
        try {
            // 组装融云消息记录数据
            $data = [
                'member_id' => $param['member_id'],
                'userId' => $param['mine']['id'],
                'targetId' => $param['to']['id'],
                'msg' => $param['mine']['content'],
                'type' => $param['to']['type']
            ];
            model('rong_msg')->save($data);

            // 检查两个用户之间是否好友  首先获取缓存
            cache('friends_' .  $param['to']['type'] . '_' . $param['mine']['id'], null);
            if(!$friends = cache('friends_' .  $param['to']['type'] . '_' . $param['mine']['id'])) {
                // 如果没有缓存，先获取好友列表数据
                $friends = model('rong_member_friend')->where('user_id', $param['mine']['id'])->where('type', $param['to']['type'])->column('target_id');
                $friends = implode(',', $friends);
                cache('friends_' . $param['to']['type'] . '_' . $param['mine']['id'], $friends);
            }

            $friends = explode(',', $friends);

            if (!in_array($param['to']['id'], $friends)) {
                // 如果两个人还不是好友，添加记录
                $friend_data = [
                    'user_id' => $param['mine']['id'],
                    'target_id' => $param['to']['id'],
                    'type' => $param['to']['type'],
                    'group' => $param['to']['type'] == 'kefu' ? 'kefu' : 'friend',
                    'update_time' => time(),
                ];
                model('rong_member_friend')->save($friend_data);
                // 更新缓存
                $friends = implode(',', $friends) . ',' . $param['to']['id'];
                cache('friends_' .  $param['to']['type'] . '_' . $param['mine']['id'], $friends);
            } else {
                // 如果已经是好友，更新时间
                model('rong_member_friend')->save(['update_time' => time()], ['user_id' => $param['mine']['id'], 'target_id' => $param['to']['id'], 'type' => $param['to']['type']]);
            }

            $rong_content = str_replace('"', "'", $param['mine']['rong_content']); // 提交到融云的json字符串使用的是双引号，所以先把内容中的双引号改为单引号，防止符号冲突发送失败

            if (preg_match("/<img class='layui-layim-photos' src='/", $rong_content)) {
                $imageUri = substr($param['mine']['content'], 4, -1);
                $imageUri = str_replace('-100', '-500', str_replace('"', "'", $imageUri)); // 提交到融云的json字符串使用的是双引号，所以先把内容中的双引号改为单引号，防止符号冲突发送失败
                $content = base64_encode(file_get_contents($imageUri));
                // 如果匹配到图片数据，发送图片信息
                if ($param['to']['type'] == 'friend') {
                    // 发送私聊消息
                    $str_data = [
                        'fromUserId' => $param['mine']['id'],
                        'toUserId' => $param['to']['id'],
                        'objectName' => 'RC:ImgMsg',
                        'content' => '{"content":"'.$content.'", "imageUri" : "'.$imageUri.'", "user":{"id":"'.$param['mine']['id'].'", "name":"'.$param['mine']['username'].'","portrait":"'.$param['mine']['avatar'].'", "type":"'.$param['to']['type'].'", "content":"'.$imageUri.'"}, "extra":"helloExtra"}'
                    ];

//                    dump($str_data);
                    $str = http_build_query($str_data);
//            $str = json_encode($str_data);
                    $url = 'http://api.cn.ronghub.com/message/private/publish.json';
                } else if ($param['to']['type'] == 'group') {
                    // 发送群消息
                    $url = 'http://api.cn.ronghub.com/message/group/publish.json';
                    $str_data = [
                        'fromUserId' => $param['mine']['id'],
                        'toGroupId' => $param['to']['id'],
                        'objectName' => 'RC:ImgMsg',
                        'content' => '{"content":"'.$content.'", "imageUri" : '.$imageUri.', "user":{"id":"'.$param['mine']['id'].'","name":"'.$param['mine']['username'].'","portrait":"'.$param['mine']['avatar'].'", "type":"'.$param['to']['type'].'", "content":"'.$imageUri.'"}, "extra":"helloExtra"}'
                    ];
                    $str = http_build_query($str_data);
                } else {
                    throw new Exception('消息类型错误');
                }
            } else {
                //  发送文本消息
                if ($param['to']['type'] == 'friend') {
                    // 发送私聊消息
                    $str_data = [
                        'fromUserId' => $param['mine']['id'],
                        'toUserId' => $param['to']['id'],
                        'objectName' => 'RC:TxtMsg',
                        'content' => '{"content":"'.$rong_content.'", "user":{"id":"'.$param['mine']['id'].'","name":"'.$param['mine']['username'].'","portrait":"'.$param['mine']['avatar'].'", "type":"'.$param['to']['type'].'", "content":"'.$param['mine']['content'].'"}, "extra":"helloExtra"}'
                    ];
                    $str = http_build_query($str_data);
//            $str = json_encode($str_data);
                    $url = 'http://api.cn.ronghub.com/message/private/publish.json';
                } else if ($param['to']['type'] == 'group') {
                    // 发送群消息
                    $url = 'http://api.cn.ronghub.com/message/group/publish.json';
                    $str_data = [
                        'fromUserId' => $param['mine']['id'],
                        'toGroupId' => $param['to']['id'],
                        'objectName' => 'RC:TxtMsg',
                        'content' => '{"content":"'.$rong_content.'", "user":{"id":"'.$param['mine']['id'].'","name":"'.$param['mine']['username'].'","portrait":"'.$param['mine']['avatar'].'", "type":"'.$param['to']['type'].'", "content":"'.$param['mine']['content'].'"}, "extra":"helloExtra"}'
                    ];
                    $str = http_build_query($str_data);
                } else {
                    throw new Exception('消息类型错误');
                }
            }



            $data = self::https_request($url, $str);

            Db::commit();
            return api_return(200, $data);
        } catch (\Exception $e) {
            Db::rollback();
            return api_return(0, '', $e->getMessage());
        }
    }

    /**
     * 获取融云聊天数据列表
     * @param $param
     * @return array
     */
    public static function get_rong_msg_list($param) {
        try {
            $rong_member_info = model('rong_member_info')->get(['member_id' => $param['member_id']]);

            $list = model('rong_member_relation')->where('userId', $rong_member_info->userId)->order('update_time desc')->select();
            $data = [];
            foreach ($list as $v) {
                $target = explode('_', $v->targetId);
                $data[] = [
                    'targetId' => $v->targetId,
                    'headimgurl' => $v->target_headimgurl,
                    'nickname' => $v->target_nickname,
                    'msg' => $v->last_msg,
                    'type' => $v->type,
                    'id' => $v->type == 3 ? $target[1] : 0
                ];
            }
            return api_return(200, $data);
        } catch (\Exception $e) {
            dump($e->getMessage());
            return api_return(0, '', $e->getMessage());
        }
    }

    /**
     * 根据userId获取融云信息
     * @param $param
     * @return array
     */
    public static function get_member_rong_info_by_userId($param) {
        try {
            $user = explode('_', $param['userId']);
            if ($user[0] == 'jx') {
                $target_member_info = model('rong_member_info')->get(['userId' => $param['userId']]);
                if ($target_member_info->member->shop && $target_member_info->member->shop->status == 2) {
                    $data['headimgurl'] = get_img_url($target_member_info->member->shop->logo);
                    $data['nickname'] = $target_member_info->member->shop->name;
                } else {
                    $data['headimgurl'] = get_img_url($target_member_info->member->memberRoleInfo->headimgurl);
                    $data['nickname'] = $target_member_info->member->memberRoleInfo->nickname;
                }
            } else if ($user[0] == 'activity') {
                $activity = model('activity')->get(['id' => $user[1]]);
                if ($activity) {
                    $data['headimgurl'] = get_img_url($activity->image_1);
                    $data['nickname'] = $activity->name;
                } else {
                    $data['headimgurl'] = '';
                    $data['nickname'] = '';
                }
            } else {
                throw new \Exception('参数错误！');
            }

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, '', $e->getMessage());
        }
    }

    /**
     * 获取融云对话数据
     * @param $param
     * @return array
     */
    public static function get_member_rong_dialogue($param) {
        try {
            $rong_member_info = model('rong_member_info')->get(['member_id' => $param['member_id']]);
            if (isset($param['targetId'])) {
                $targetId = $param['targetId'];
             } else if (isset($param['id'])) {
                // 如果传的是店铺ID则获取  当前用户和店铺之间的
                $shop = model('shop')->get(['id' => $param['id']]);
                $targetId = 'jx_rong_' . $shop->member_id;
            } else {
                throw new \Exception('参数错误');
            }
            $list = model('rong_msg')->where('(userId = "' .$rong_member_info->userId .'" AND targetId = "' . $targetId. '") OR (targetId = "' .$rong_member_info->userId .'" AND userId = "' . $targetId . '")')->select();

            //  获取我的头像和昵称
            $me_headimgurl = get_img_url($rong_member_info->member->memberRoleInfo->headimgurl);
            $me_nickname = $rong_member_info->member->memberRoleInfo->nickname;


            //  获取对方的头像和昵称
            $target_member_info = model('rong_member_info')->get(['userId' => $targetId]);
            $to_headimgurl = get_img_url($target_member_info->member->memberRoleInfo->headimgurl);
            $to_nickname = $target_member_info->member->memberRoleInfo->nickname;


            $data = [];
            foreach ($list as $v) {
                if ($v->userId == $rong_member_info->userId) {
                    $data['list'][] = [
                        'headimgurl' => $me_headimgurl,
                        'nickname' => $me_nickname,
                        'action' => 'send',
                        'msg' => $v->msg,
                    ];
                } else {
                    $data['list'][] = [
                        'headimgurl' => $to_headimgurl,
                        'nickname' => $to_nickname,
                        'action' => 'accept',
                        'msg' => $v->msg,
                    ];
                }
            }
            $data['peer_headimgurl'] = $to_headimgurl;
            $data['peer_nickname'] = $to_nickname;
            $data['me_headimgurl'] = $me_headimgurl;
            $data['me_nickname'] = $me_nickname;
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, '', $e->getMessage());
        }
    }

    /**
     * 获取群组成员
     * @param $param
     * @return array
     */
    public static function get_group_members($param) {
        $member_list = model('activity_participation')->where('activity_id', $param['id'])->select();

        // 活动信息
        $activity = model('activity')->where('id', $param['id'])->find();

        $list = [];

        if ($activity) {
            $list[] = [
                "username" => $activity->orderMember->memberRoleInfo->nickname
                ,"id" => $activity->member_id
                ,"avatar" => $activity->orderMember->memberRoleInfo->headimgurl
                ,"identity" => 1
            ];
        }


        if ($member_list) {
            foreach ($member_list as $v) {
                $list[] = [
                    "username" => $v->activityParticipationMember->memberRoleInfo->nickname
                    ,"id" => $v->member_id
                    ,"avatar" => $v->activityParticipationMember->memberRoleInfo->headimgurl
                    ,"identity" => 0
                ];
            }
        }

        $data = [
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'list' => $list
            ]
        ];
        return api_return(200, $data);
    }

    /**
     * 获取聊天记录
     * @param $param
     * @return array
     */
    public static function get_msg_list($param) {
        if ($param['type'] == 'group') {
            $msg_list = model('rong_msg')->where('targetId', $param['id'])->where('type', 'group')->select();
        } else {
            $msg_list = model('rong_msg')
                ->where("targetId =  $param[id] AND userId = $param[member_id]")
                ->whereOr("userId =  $param[id] AND targetId = $param[member_id]")
                ->where('type', $param['type'])
                ->select();
        }

        $list = [];
        if ($msg_list) {
            foreach ($msg_list as $v) {
                $list[] = [
                    "username" => $v->member->memberRoleInfo->nickname
                    ,"id" => $v->member_id
                    ,"avatar" => $v->member->memberRoleInfo->headimgurl
                    ,'timestamp' => date('Y-m-d H:i:s', $v->create_time)
                    ,'content' => $v->msg
                ];
            }
        }
        return api_return(200, $list);
    }
}